# -*- coding: utf-8 -*-
'''
    :file: models.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/02/10 16:16:49
'''
from operator import add
from re import findall
import os
from datetime import datetime, time
import re
from time import sleep
from sqlalchemy.sql.expression import false
from sqlalchemy.sql.functions import user
#
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import BadSignature, SignatureExpired, TimedJSONWebSignatureSerializer as Serializer
#
import sqlalchemy as sa
from flask import current_app
from app.extensions import db

# 用户数据库模型
class User(db.Model):
    id = sa.Column(sa.Integer, primary_key=True)
    username = sa.Column(sa.String(20))
    password_hash = sa.Column(sa.String(128))
    address = sa.Column(sa.String(60))
    email = sa.Column(sa.String(260))
    last_time = sa.Column(
        sa.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    power = sa.Column(sa.Integer, default=0)
    # 设置密码（加密）
    def set_password(self, password):
        if len(password) < 6:
            raise ValueError('密码长度不够')
        self.password_hash = generate_password_hash(password)
    # 验证密码（解析）
    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)
    # 登录成功返回鉴权令牌（生成token）
    def generate_auth_token(self, expiration=3600 * 24 * 7):
        s = Serializer(current_app.config["SECRET_KEY"], expires_in=expiration)
        return s.dumps({
            'id': self.id,
            'username': self.username,
            'power': self.power
        }).decode()

    # 鉴权（验证token）
    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user

    # 生成管理员的token
    def generate_admin_token(self, expiration=3600 * 24 * 7):
        s = Serializer(current_app.config["SECRET_KEY"], expires_in=expiration)
        return s.dumps({
            'id': self.id,
            'username': './',
            'power': self.power
        }).decode()

# 系统日志模型
class LogMsg(db.Model):
    # 主键
    id = sa.Column(sa.Integer, primary_key=True)
    username = sa.Column(sa.String(20))
    # 请求主机，端口
    host = sa.Column(sa.String(50))
    port = sa.Column(sa.String(6))
    # 请求接口信息
    api_msg = sa.Column(sa.String(256))
    # 操作员等级
    ctr_lv = sa.Column(sa.Integer, default=0)
    # 是否是管理员操作
    is_admin = sa.Column(sa.Boolean, default=False)
    # 操作时间
    log_time = sa.Column(
        sa.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 测试代码
    def get_json(self):
        return {
            "id": self.id,
            "username": self.username,
            "host": self.host,
            "port": self.port,
            "api_msg": self.api_msg,
            "ctr_lv": self.ctr_lv,
            "is_admin": self.is_admin,
            "log_time": self.log_time
        }


# DDNS配置
class DDNSCoreConfig(db.Model):
    # 主键
    id = sa.Column(sa.Integer, primary_key=True)
    # 任务名（备注）
    task_name = sa.Column(sa.String(20))
    # 解析域名
    domain_name = sa.Column(sa.String(128))
    # 阿里云SDK密钥，并加密存储
    accessKeyId_hash = sa.Column(sa.String(128))
    accessSecret_hash = sa.Column(sa.String(128))
    # 解析子域名列表
    # 一对多关系，外链RRList表
    rr_lists = db.relationship('RRList')
    # 加密函数
    def set_access(self, accessKeyId, accessSecret):
        self.accessKeyId_hash = generate_password_hash(accessKeyId)
        self.accessSecret_hash = generate_password_hash(accessSecret)

# 子域名列表
class RRList(db.Model):
    id = sa.Column(sa.Integer, primary_key=True)
    # 记录值
    rr_type = sa.Column(sa.String(128))
    # DDNS配置条目ID
    config_id = sa.Column(sa.Integer, db.ForeignKey('ddns_core_config.id'))